class Login {
    returnUrl = ""
    constructor() {
        let parm = location.search;
        // console.log(parm);
        if (parm) {
            parm = parm.split("=")[1]
            this.returnUrl = parm
        }
        // console.log(this.returnUrl);
        //绑定点击事件
        this.$(".over").addEventListener("click", this.loginBtn.bind(this))
    }
    loginBtn() {
        //先获取表单元素
        let form = document.forms.login.elements
        // console.log(form);
        let uesrname = form.uname.value.trim();
        let pwd = form.password.value.trim();
        if (!uesrname) {
            layer.tips('账号不能为空', form.uname);
            return
        }
        if (!pwd) {
            layer.tips('密码不能为空', form.password);
            return
        }
        //给服务器发请求  设置编码
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        //发送数据
        let parm = `username=${uesrname}&password=${pwd}`
        //请求
        axios.post("http://localhost:8888/users/login", parm).then(res => {
            // console.log(res);
            let { data, status } = res
            //判断服务器状态码
            if (!status == 200 || data.code !== 1) {
                layer.msg('账号或者密码错误');
                return
            }
            // console.log(data);
            //存取用户token 和 id
            localStorage.setItem("token", data.token);
            localStorage.setItem("user_id", data.user.id)
            // console.log(location.search);
            // console.log(this.returnUrl);
            this.returnUrl ? location.assign(this.returnUrl) : location.assign('./index.html')
        })
    }



    //获取节点
    $(ele) {
        let res = document.querySelectorAll(ele);
        return res.length == 1 ? res[0] : res
    }


}
new Login;